#pragma once
#include <iostream>
#include <string>
#include <time.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <unistd.h>
#include<cstring>
using namespace std;
const string path = "/home/qingguo/project27_sharedmem";
const int project = 0x1234;
const int shmsize = 4096;
const mode_t gmode = 0600;
string Hex(int x)
{
    char arr[100];
    snprintf(arr, 100, "0x%x", x);
    return arr;
}
class ShareMemory
{
private:
    void CreatShmHelper(int shmflg)
    {
        _key = ftok(path.c_str(), project);
        cout<<Hex(_key)<<endl;
        if (_key < 0)
        {
            cerr << "ftok error" << endl;
            return;
        }
        _shmid = shmget(_key, shmsize, shmflg);
        cout<<_shmid<<endl;
        if (_shmid < 0)
        {
            cerr << "shmget:" <<Hex(_key)<< endl;
            return;
        }
        return;
    }

public:
    ShareMemory()
        : _shmid(-1), _key(-1), addr(nullptr)
    {
    }
    ~ShareMemory() {}
    void CreatShm()
    {
        CreatShmHelper(IPC_CREAT | IPC_EXCL | 0666);
    }
    void GetShm()
    {
        CreatShmHelper(IPC_CREAT);
    }
    void deleteShm()
    {
        shmctl(_shmid, IPC_RMID, nullptr);
    }
    void AttachShm()
    {
        addr = shmat(_shmid, NULL, 0);
        if (-1 == (long long)addr)
            cout << "AttchShm Error" << endl;
        return;
    }
    void DetachShm()
    {
        if (addr != nullptr) // 说明挂接成功
            shmdt(addr);
    }
    int GetShmid()
    {
        return _shmid;
    }
    void *GetAddr()
    {
        return addr;
    }
    key_t GetKey()
    {
        return _key;
    }

private:
    int _shmid;
    key_t _key;
    void *addr;
};
ShareMemory shm;
struct data
{
    char status[32];     // 当前正在传递数据的状态
    char lasttime[48];   // 最新写入消息的时间
    char messsage[1024]; // 要传入的消息
};
